package com.sfang.common.base.http.filter;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.sfang.common.base.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xuzilou
 * @date 2021/4/30 9:52
 */
@Component
@Order(Integer.MIN_VALUE)
@Slf4j
@WebFilter(filterName = "LogMdcFilter", urlPatterns = "/**")
public class LogMdcFilter implements Filter {



    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String traceId = request.getHeader(Constants.TRACK_ID);
            MDC.put(Constants.TRACK_ID, StrUtil.isBlank(traceId) ? IdUtil.simpleUUID() : traceId);
            filterChain.doFilter(servletRequest, servletResponse);
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setHeader(Constants.TRACK_ID, MDC.get(Constants.TRACK_ID));
        } finally {
            MDC.clear();
        }

    }
}
